package com.zhuna.www.service;

import com.zhuna.www.constant.RechargeStatus;
import com.zhuna.www.dao.RechargeDAO;
import com.zhuna.www.dao.UserDAO;
import com.zhuna.www.dao.impl.UserDAOImp1;
import com.zhuna.www.po.RechargeRecord;
import com.zhuna.www.util.JDBCutil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.UUID;

public class ReChargeService {
    /*
      充值事务管理
     @param userId 用户ID
     * @param amount 充值金额
     * @return 操作结果（成功/失败原因）
     */
    private UserDAO userDao = new UserDAOImp1();
    public RechargeDAO rechargeDao = new RechargeDAO();

    //手动管理事务
    public String recharge(int userId, double amount) {
        Connection conn = null;
        try {
            // 1. 开启事务
            conn = JDBCutil.beginTransaction();
            // 2. 生成唯一流水号
            String transactionId = UUID.randomUUID().toString().replace("-", "");

            // 3. 插入充值记录
            RechargeRecord record = new RechargeRecord();
            record.setUserId(userId);
            record.setAmount(amount);
            record.setTransactionId(transactionId);
            record.setStatus(RechargeStatus.PENDING);
            if (rechargeDao.insertRecord(conn, record) <= 0) {
                throw new SQLException("插入充值记录失败");}

                // 4. 更新用户余额
            if (userDao.updateWalletBalance(conn, userId, amount) <= 0) {
                    throw new SQLException("更新余额失败");
                }

            // 5. 提交事务
            JDBCutil.commitTransaction(conn);
            return "充值成功，您的流水号：" + transactionId;

        }catch (SQLException e){
            //6.回滚事务
            JDBCutil.rollbackTransaction(conn);
            return "充值失败：" + e.getMessage();

        }
    }




}
